package cn.vc.content.controller.video;

import cn.vc.auth.entity.po.VUser;
import cn.vc.basicmodule.entity.Result;
import cn.vc.media.entity.po.MediaFiles;
import cn.vc.media.feign.clients.MediaFilesClient;
import cn.vc.content.entity.video.dto.VideoDto;
import cn.vc.content.entity.video.po.Video;
import cn.vc.content.service.video.VideoHistoryService;
import cn.vc.content.service.video.VideoService;
import cn.vc.content.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/video")
public class VideoController {
    @Resource
    private VideoService videoService;
    @Resource
    private VideoHistoryService videoHistoryService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MediaFilesClient mediaFilesClient;



    /**
     * 发布视频
     * @param title 标题
     * @param intro 简介
     * @param needSMember 是否需要S会员
     */
    @PostMapping("/publish")
//    @PreAuthorize("hasAnyAuthority('ordinary')")
    public Result<?> publish(@RequestParam String title, @RequestParam String intro, @RequestParam Integer videoTotalTime, /*@RequestParam String communitiesId,*/
                          @RequestParam String coverUrl, @RequestParam Long mediaId, @RequestParam boolean needSMember) throws IOException {
        VUser vUser = SecurityUtil.getUser();
        if (vUser==null) return Result.NOT_LOGGED_IN();
        Result<MediaFiles> mediaFilesResult = mediaFilesClient.selectById(mediaId);
        if (mediaFilesResult.getCode()==0) return new Result<>(0);
        // 是否保存成功
        boolean bo = true;
        UUID id = UUID.randomUUID();//文件名
        Video video = new Video();
        video.setUsername(vUser.getUsername());
        video.setTitle(title);
        video.setIntro(intro);
        video.setCoverUrl(coverUrl);
        video.setMediaId(mediaId);
        video.setNeedSMember(needSMember);
//        video.setCommunitiesId(communitiesId);
        video.setUserId(vUser.getId());
        bo = videoService.add(video);
//        amqpTemplate.convertAndSend("video.direct", "save", videoService.selectCurrentId());
        return new Result<>(bo);
    }
    /**
     * 审核通过
     */
    @PostMapping("/audit/{id}")
    public void passTheAudit(@PathVariable("id") Long id) {
        videoService.passTheAudit(id);
    }


    /**
     * 查询所有草稿
     * @return
     */
    @GetMapping("/1")
    public List<VideoDto> selectDraft() {
        List<VideoDto> videoDtoList = videoService.selectAllByIsDraft();
        return videoDtoList;
    }
    /**
     * <h2>通过ID查询草稿</h2>
     * @return
     */
    @GetMapping("/1/{id}")
    public Result<?> selectDraftById(@RequestHeader(value = "token") String token,
                                     @PathVariable("id") String id) {
        VUser vUser = SecurityUtil.getUser();
        if (vUser==null) return Result.NOT_LOGGED_IN();
        String json = stringRedisTemplate.opsForValue().get("video:"+vUser.getId()+":"+id);
        return new Result<>(1, json);
    }
    /**
     * <h2>查询所有视频</h2>
     * @return
     */
    @GetMapping("/2")
    public Result<?> selectAll() {
        return new Result<>(1, videoService.selectAllByNotDraft());
    }
    /**
     * 分页查询视频
     * @param current 当前页
     * @param size 每页显示条数
     */
    @GetMapping("/2/page")
    public Result<List<VideoDto>> selectPage(@RequestParam("current") Long current, @RequestParam("size") Long size) {
        // 限制每页最大条数
        if (size>100) return new Result<>(0, null, "查询每页显示条数过大！");
        List<VideoDto> videoDtoList = videoService.selectPage(current, size);
        return new Result<>(1, videoDtoList, "查询成功！");
    }
    /**
     * <h2>通过ID查询视频</h2>
     * @return
     */
    @GetMapping("/2/{id}")
    public Result<?> selectSaveById(@PathVariable("id") Long id) {
        VideoDto videoDto = videoService.selectById(id);
        // 视频不存在
        if (videoDto==null) return new Result<>(0);
        VUser vUser= SecurityUtil.getUser();
        // 登录用户的请求
        if (vUser!=null) {
            // 确定为登录用户后记录视频历史记录
            // 添加观看视频记录
            videoHistoryService.records(vUser.getId(), id);
            // 添加点击数
            videoService.tap(id);
            // 需要S会员且用户不为会员
            if (videoDto.getNeedSMember()&&vUser.getMember()!=1) {
                videoDto.setVideoUrl("");
            }
        } else {
            // 需要S会员，且未登录
            if (videoDto.getNeedSMember()) {
                videoDto.setVideoUrl("");
            }
        }
        return new Result<>(1, videoDto);
    }
    /**
     * <h2>通过userId查询视频</h2>
     * @return
     */
    @GetMapping("/3/{id}")
//    @PreAuthorize("hasAnyAuthority('ordinary')")
    public Result<List<VideoDto>> selectByUserId(@PathVariable("id") Long userId) {
        List<VideoDto> videoDtoList = videoService.selectByUserId(userId);
        return new Result<>(1, videoDtoList);
    }
    @GetMapping("/4")
    public Result<?> selectByTapNum() {
        List<VideoDto> videoList = videoService.selectAllByNotDraft();
        videoList.sort((o1, o2)-> (int)(o2.getTapNum() - o1.getTapNum()));
        return new Result<>(1, videoList, "查询成功！");
    }
}
